// pages/service/service_index/service_index.js
const db = wx.cloud.database({});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    question: [],



    user_url: 'cloud://peiyoukaoliantong-8e910u9ad85580.7065-peiyoukaoliantong-8e910u9ad85580-1317756011/静态资源/null_head.png',
    user_title: '',
    files: [],
    questions: '',
    time: '',
    cloudfiles: [],
    user_default: '',
    user_type: '',
    show: false,
    filePath: [],
    _id:'',
      //画廊功能
      imgUrls: [],
      img_view: false,
    img_view_index: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let openId = wx.getStorageSync('openId')
 db.collection("user").doc(openId).get()
    .then(res => {
      this.setData({
        user_type:res.data.user_type,
      })
      console.log(res.data.user_type)
    })
    this.setData({
      selectFile: this.selectFile.bind(this),
      uplaodFile: this.uplaodFile.bind(this),
      _id:options.id
    })
     db.collection("question").doc(options.id).get()
      .then(res => {
        console.log(res.data)
        this.setData({
          question: res.data
        })
      })



  },
new(){
  let _id = this.data._id
  let res = db.collection("question").doc(_id).get()
  .then(res => {
    console.log(res.data)
    this.setData({
      question: res.data,
      _id:res.data._id
    })
  })

},

  selectFile(files) {
    console.log('files', files)
    // 返回false可以阻止某次文件上传
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  uplaodFile(files) {
    console.log('files', files)
    return new Promise((resolve, reject) => {
      resolve({
        "urls": files.tempFilePaths
      })
    })
  },
  uploadError(e) {
    console.log('upload error', e.detail)
  },
  uploadSuccess(e) {
    console.log('upload success', e.detail.urls)
    this.setData({
      filePath: e.detail.urls
    })
  },







  async post() {

    // 获取openid
    let openId = wx.getStorageSync('openId')
    // console.log(openId)
    // 查询数据库中是否有用户数据
    let res = db.collection("user").doc(openId).get()
      .then(res => {
        this.setData({
          user_url: res.data.user_url,
          user_title: res.data.user_title,
          user_type: res.data.user_type
        })
      })


    wx.showLoading({
      title: '上传中...',
    })
    let files = this.data.filePath

    console.log('文件本地地址', files)
    var newDateTime = Date.parse(new Date())
    var time = this.formatDate(newDateTime) //转换时间戳
    for (var i = 0; i < files.length; i++) {

      let filepath = files[i]
      await wx.cloud.uploadFile({
          cloudPath: 'question_img/' + newDateTime + '-' + i + '.png', // 上传至云端的路径
          filePath: filepath // 小程序临时文件路径，需结合小程序相关 API 获取
        })
        .then((res) => {
          this.setData({
            time: time
          })
          this.data.cloudfiles = this.data.cloudfiles.concat(res.fileID);


        });
    }
    //****************** 连接数据库上传全部信息*******************************************/
    let cloudfiles = this.data.cloudfiles
    let user_title = this.data.user_title
    let user_url = this.data.user_url
    let questions = this.data.questions
    let user_type = this.data.user_type
    let _id = this.data.question._id
    const _ = db.command
    db.collection('question').doc(_id).update({
        data: {
          huifu: _.push({
            question: questions,
            user_title: user_title,
            user_url: user_url,
            files: cloudfiles,
            time: time,
            user_type: user_type
          })
        }


      })
      .then(res => {
        wx.hideLoading()

        wx.showToast({
          title: '发表成功!',
          icon: "success",
          duration: 2000,
          mask: true
        })


 this.new();
        this.setData({
          camar: false,
          files: [],
          cloudfiles: [],
          show: false
        })


        wx.navigateTo({
          url: '/pages/service/service_list/service_list',
        })
      })
      .catch(res => {
        wx.showToast({
          title: '发表失败!',
          icon: "woang",
          duration: 2000,
          mask: true
        })

      })
  },
  getInputValue: function () {
    let content = this.data.content
  },



  // 时间戳转换函数
  formatDate: function (inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
  },

  next() {
    this.setData({
      show: true,
      files: [],
      cloudfiles: []
    });
  },
  // 用户点击已经解决按钮
  ok() {
    let _id = this.data.question._id
    db.collection('question').doc(_id).update({
      data: {
        date: true
      }
    })

    this.onPullDownRefresh();
  },
  onClose() {
    this.setData({
      show: false
    });
  },


  //图片点击事件
	//画廊
	img_view: function (e) {
		this.setData({
			img_view: true,
			imgUrls: [],
			img_view_index: ''
		})
		console.log('dianjibig',e)
		var arr = e.currentTarget.id.split(",");
		console.log('显示的照片',arr)
		this.setData({
			img_view: true,
			imgUrls: arr,
			img_view_index: e.target.id
		})
	},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.new();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  add() {
    wx.navigateTo({
      url: '/pages/service/service_question/service_question',
    })
  }
})